// 和用户相关的路由地址
const express = require("express");

let { uploadimg } = require("../util");
const md5 = require("md5");
const userModel = require("../models/userModel");
let router = express.Router();

router.get("/getdata", async (req, res) => {
  // 获取用户信息
  try {
    let usersData = await userModel.find();
    let totalCount = usersData.length;
    let perpage = 3;

    let pageCount = Math.ceil(totalCount / perpage);

    let { p } = req.query; // 当前的页码；
    console.log(p);

    let filterData=await userModel.find().skip((p-1)*perpage).limit(perpage)
    res.json({
      info: "获取用户信息成功",
      pageCount,
      status: 1,
      users: filterData,
    });
  } catch (err) {
    res.json({
      info: "获取用户信息失败",
      status: 0,
      err,
    });
  }
});

// 接收前端提交过来的数据和文件
router.post("/adduser", async (req, res) => {
  console.log(req.body);
  try {
    let reslut = await uploadimg(req);
    console.log(reslut);
    reslut.pwd = md5(reslut.pwd);
    reslut.time = new Date().toLocaleDateString();
    console.log(reslut);
    //    把密码加密之后添加到数据库
    let resobj = await userModel.create(reslut);
    console.log(resobj);
    res.json({
      info: "添加用户成功",
      status: 1,
    });
  } catch (err) {
    res.json({
      info: "添加用户失败",
      status: 0,
      err,
    });
  }
});

// 删除用户信息
router.delete("/deluser", async (req, res) => {
  // 获取delete 传递过来的id数据
  let { _id } = req.query;
  console.log(_id);
  try {
    // 通过 id 删除 数据库里对应的数据
    let resobj = await userModel.deleteOne({ _id });
    console.log(resobj);
    res.json({
      info: "删除成功",
      status: 1,
      resobj,
    });
  } catch (err) {
    res.json({
      info: "删除失败",
      status: 0,
      err,
    });
  }
});

module.exports = router;
